
import Foundation
//import CoreLocation
import UIKit
import Photos
import AVFoundation

class RXPermissionUtils: NSObject {
    
    static let appName = Bundle.main.infoDictionary!["CFBundleDisplayName"] ?? ""
    
    typealias Result = ((Bool) -> Void)
    typealias PermissionResult = (() -> Void)

    
    
    static func nomalWindow() -> UIWindow {
       var window = UIApplication.shared.connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .flatMap { $0.windows }
            .first(where: { $0.isKeyWindow })!
       for item in UIApplication.shared.windows {
           if item.windowLevel == .normal {
               window = item
           }
       }
       return window
   }
    
    @objc static func currentVC() ->UIViewController{
        //UIApplication.shared.keyWindow 即将被弃用
        var vc = UIApplication.shared.connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .flatMap { $0.windows }
            .first(where: { $0.isKeyWindow })?.rootViewController
        
        if (vc?.isKind(of: UITabBarController.self))! {
            vc = ((vc as! UITabBarController).selectedViewController as! UINavigationController).visibleViewController
        }else if (vc?.isKind(of: UINavigationController.self))!{
            vc = (vc as! UINavigationController).visibleViewController
        }else if ((vc?.presentedViewController) != nil){
            vc =  vc?.presentedViewController
        }
        
        return vc!
        
    }
    static func showSystemAlert(title: String?, message: String?) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let action1 = UIAlertAction(title: NSLocalizedString("取消", comment: ""), style: .cancel) { (act) in
            
        }
        let action2 = UIAlertAction(title: NSLocalizedString("确定", comment: ""), style: .default) { (act) in
           jumpIPhoneSetting()
        }
        alert.addAction(action1)
        alert.addAction(action2)
        currentVC().present(alert, animated: true, completion: nil)
    }
    
    
    static func jumpIPhoneSetting() {
        UIApplication.shared.open(URL.init(string: UIApplication.openSettingsURLString)!, options: [:],
                                  completionHandler: {
                                    (success) in
        })
    }
    
    
    @objc static func albumAndCamera(type: UIImagePickerController.SourceType, suc:PermissionResult?) {
        if type == .photoLibrary {
            albumPermission { (granted) in
                DispatchQueue.main.async {
                    if granted {
                        suc?()
                    }else{
                        showSystemAlert(title: NSLocalizedString("无法打开相册", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app访问相册", comment: ""))
                    }
                }
            }
        }else if type == .camera {
            cameraPermission { (granted) in
                DispatchQueue.main.async {
                    if granted {
                        suc?()
                    }else{
                        showSystemAlert(title: NSLocalizedString("无法使用相机", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app访问相机", comment: ""))
                    }
                }
            }
        }
    }
    
    @objc static func albumAndCamera(type: UIImagePickerController.SourceType, suc:PermissionResult?, fail:PermissionResult?) {
        if type == .photoLibrary {
            albumPermission { (granted) in
                DispatchQueue.main.async {
                    if granted {
                        suc?()
                    }else{
                        fail?()
                        showSystemAlert(title: NSLocalizedString("无法打开相册", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app访问相册", comment: ""))
                    }
                }
            }
        }else if type == .camera {
            cameraPermission { (granted) in
                DispatchQueue.main.async {
                    if granted {
                        suc?()
                    }else{
                        fail?()
                        showSystemAlert(title: NSLocalizedString("无法打开相机", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app访问相机", comment: ""))
                    }
                }
            }
        }
    }
    
//    
//    @objc static func microphone(suc:PermissionResult?) {
//        microphonePermission { (granted) in
//            DispatchQueue.main.async {
//                if granted {
//                    suc?()
//                }else{
//                    showSystemAlert(title: NSLocalizedString("无法使用麦克风", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app访问麦克风", comment: ""))
//                }
//            }
//        }
//    }
//    
//    
//    @objc static func location(result: Result?) {
//        if !CLLocationManager.locationServicesEnabled() {
//            showSystemAlert(title: NSLocalizedString("无法获取定位", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app使用定位", comment: ""))
//            return
//        }
//        if CLLocationManager.authorizationStatus() == .denied {
//            
//        }
//    }
//    
//    
    
    private static func albumPermission(result: Result?){
        if result == nil { return }
        let status = PHPhotoLibrary.authorizationStatus()
        if status == .restricted || status == .denied {

            result?(false)
            return
        }
        if status == .authorized {

            result?(true)
            return
        }

        PHPhotoLibrary.requestAuthorization { (authStatus) in
            let hasAuth = authStatus == .authorized
            result?(hasAuth)
        }
    }

    
    private static func cameraPermission(result: Result?) {
        if result == nil { return }
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        if status == .restricted || status == .denied {

            result?(false)
            return
        }
        if status == .authorized {

            result?(true)
            return
        }
        AVCaptureDevice.requestAccess(for: .video) { (granted) in
            result?(granted)
        }
    }
    
//
//    private static func microphonePermission(result: Result?) {
//        if result == nil { return }
//        let status = AVCaptureDevice.authorizationStatus(for: .audio)
//        if status == .restricted || status == .denied {
//
//            result?(false)
//            return
//        }
//        if status == .authorized {
//
//            result?(true)
//            return
//        }
//        AVCaptureDevice.requestAccess(for: .audio) { (granted) in
//            result?(granted)
//        }
//    }
//
    
}
